<?php
/**
 * Shopping cart controller
 */
require_once 'Mage/Checkout/controllers/CartController.php';
require_once 'Mage/Checkout/block/cart/crosssell.php';
class Mageex_AjaxCart_CartController extends Mage_Checkout_CartController
{
    private function _sendJson(array $data = array())
    {
        // clear message stack
        $storageAreas[] = Mage::getSingleton('checkout/session');
        $storageAreas[] = Mage::getSingleton('catalog/session');
        foreach ($storageAreas as $storage){
            $storage->getMessages(true);
        }

        @header('Content-type: application/json');
		
        echo json_encode($data);
        exit();
    }

    private function _updateLayout($handles)
    {
        $handles = Zend_Json::decode($handles);
        foreach ($handles as $handle) {
            $this->getLayout()->getUpdate()->addHandle($handle);
        }
        $this->loadLayout(false, false);
        $this->_layoutXml = $this->getLayout()->getUpdate()->asSimplexml();
    }

    private function _addReferenceBlocks( Mage_Core_Model_Layout_Element $node)
    {
        if (!function_exists('xml2array')) {
            function xml2array($data)
            {
              if (is_object($data)) $data = get_object_vars($data);
              return (is_array($data)) ? array_map(__FUNCTION__, $data) : $data;
            }
        }
        
        $xmlBlocks = array();
        foreach ($node->block as $block) {

            $references = $this->_layoutXml->xpath("//reference[@name='" . $block['name'] . "']");
            
            foreach ($references as $reference) {
                $referenceBlock = $reference->block;
                if ($referenceBlock) {
                    $referenceBlock = $this->_addReferenceBlocks($referenceBlock);
                }
                $child = $block->addChild('block', $reference->block);
                $attributes = xml2array($reference->block);
                if (!isset($attributes['@attributes'])) {
                    continue;
                }
                
                $attributes = $attributes['@attributes'];
                foreach ($attributes as $key => $value) {
                    $child->addAttribute($key, $value);
                }

            }
        }
        return $node;
    }

    private function _genarateBlock($blockName)
    {
        $nodes = $this->_layoutXml->xpath("//block[@name='" . $blockName . "']");
		
        if (!count($nodes)) {
            return '';
        }
        //hardcoded
        foreach ($nodes as &$node) {
            $node['parent'] = 'root';
            $node = $this->_addReferenceBlocks($node);
        }//print_r($nodes);die();

        $this->getLayout()->generateBlocks($nodes);
       
        $block = $this->getLayout()->getBlock($blockName);
        
        if (!$block) {
            return '';
        }
        return $block->toHtml();
    }

    protected function _generateResponse($message = '', $abort=null)
    {
        $response = array();
        if (!empty($message)) {
            $response['message'] = $message;
        }
		if($abort == 'add'){
			$response['action'] = 'add';
		}
		if($abort == 'update'){
			$response['action'] = 'update';
		}
        $response['topLinkCart'] = $this->_getTopCheckoutCartLinksContent();
        if($abort == null){
			$checkoutCartContent = $this->_genarateBlock('checkout.cart');
        }
		$pattern = '/(\<table id\=\"shopping\-cart\-table\" class\=\"data\-table cart\-table\"\>.*\<\/table\>)/sU';
        preg_match($pattern, $checkoutCartContent, $matches);
        if (isset ($matches[1]) && !empty ($matches[1])) {
            $response['shoppingCartTable'] = $matches[1];
        }
		 if($abort == null){
			$response['checkoutCartTotals'] = $this->_genarateBlock('checkout.cart.totals');
        }
		
//        $response['checkoutCart'] = $checkoutCartContent;
        $subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
        $subTotal = sprintf("%10.2f", $subTotal);
		$response['miniCart'] 			= '<span class="price">$'.$subTotal.'</span>';//$this->_genarateBlock('cart_sidebar');
		$response['crosssell'] 			= $this->getItems();
        $response['totalItemInCart'] 	= Mage::helper('checkout/cart')->getSummaryCount();
		$response['viewcart'] 			= $arrProduct = $this->getProductInCart();
		return $response;
    }
	public function indexAction()
	{
		
        $isAjaxProRequest = $this->getRequest()->getParam('ajaxpro', false);
        
		if (!$isAjaxProRequest || !Mage::getStoreConfig('ajaxcart/general/enabled')) {
			
            return  parent::updatePostAction();
        }

        try {
            return $this->_sendJson($this->_generateResponse(__('Update successful'), 'notnull'));
        }
        catch (Exception $e) {
            $message = $e->getMessage();
        }
        $this->_sendJson(array(
            'message' => __($message)
        ));
	}
	public function getProductInCart()
	{
		$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
		$arrProduct = array();
		$_product = Mage::getModel('catalog/product');
		foreach ( $items as $item  ) {
			$_product->load($item->getProductId());
			$arrTmp['cartid']	= $item->getId();
			$arrTmp['name'] 	= $item->getName();
			$arrTmp['price']	= Mage::helper('checkout')->formatPrice($_product->getPrice());
			$arrTmp['qty'] 		= $item->getQty();
			$arrTmp['subtotal'] = Mage::helper('checkout')->formatPrice(Mage::helper('checkout')->getSubtotalInclTax($item));
			$arrTmp['urlImg'] 	= $_product->getImageUrl();
			$arrTmp['url'] 		= Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK) . $_product->getUrlPath();
			$arrTmp['urlRemove']= Mage::helper('checkout/cart')->getRemoveUrl($item);
			$arrProduct[] = $arrTmp;
		}
		if(count($arrProduct)>0){
			return $arrProduct;
		}
		return;
	}
    private function _getTopCheckoutCartLinksContent()
    {
        $count = Mage::helper('checkout/cart')->getSummaryCount();

        if( $count == 1 ) {
            $text = $this->__('Item: %s', $count);
        } elseif( $count > 0 ) {
            $text = $this->__('Items: %s', $count);
        } else {
            $text = $this->__('Item: 0');
        }

        return '<a class="top-link-cart" title="' . $text
            . '" href="' . Mage::getBaseUrl() . 'checkout/cart/" style="color:#FFFFFF">'
            . $text . '</a>';
    }



    /**
     * Add product to shopping cart action
     */
    public function addAction()
    {
		
        $isAjaxProRequest = $this->getRequest()->getParam('ajaxcart', false);
		
        $hasAttributeProduct = (bool)('cart' == $this->getRequest()->getParam('options', false));

//        $isUploadFile = $this->getRequest()->getParam('isuploadfile', false);
        if ($isAjaxProRequest && $this->getRequest()->getParam('onlyblocks', false)) {
            try {
                $this->_updateLayout($this->getRequest()->getParam('handles'));
                $this->_sendJson($this->_generateResponse(), 'add');
            } catch (Exception $e) {
                $message = $e->getMessage();
                $this->_getSession()->addException($e, __($message));
                $this->_sendJson(array(
                    'redirectUrl' => $this->_getRefererUrl(),
                    'message' => __($message)
                ));
            }
        }

        if ((!$isAjaxProRequest && !$this->getRequest()->isXmlHttpRequest()) ||
            !$this->getRequest()->isXmlHttpRequest() ||
            !Mage::getStoreConfig('ajaxcart/general/enabled')) {

            return parent::addAction();
        }
        
        $cart   = $this->_getCart();
        $params = $this->getRequest()->getParams();

        $product= $this->_initProduct();
        $related= $this->getRequest()->getParam('related_product');

        /**
         * Check product availability
         */
        if (!$product) {
            $this->_sendJson(array(
                'redirectUrl' => $this->_getRefererUrl(),
                'message' => __('Product not available')
            ));
        }

        try {
            
            $cart->addProduct($product, $params);
            
            if (!empty($related)) {
                $cart->addProductsByIds(explode(',', $related));
            }
            
            $cart->save();

            $this->_getSession()->setCartWasUpdated(true);

            /**
             * @todo remove wishlist observer processAddToCart
             */
            Mage::dispatchEvent('checkout_cart_add_product_complete',
                array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
            );
			 //$message.= '<img src ='.$product->getProductThumbnail()->resize(75).' width="75"  style="border:1px solid #dedede;"/>';
            $message = $this->__('%s was successfully added to your shopping cart.', $product->getName());
			//$message. = $product->getId();
            $this->_updateLayout($this->getRequest()->getParam('handles'));
			
            $this->_sendJson($this->_generateResponse(__($message), 'add'));
        }
        catch (Mage_Core_Exception $e) {
            if ($this->_getSession()->getUseNotice(true)) {
                $this->_getSession()->addNotice($e->getMessage());
                $allMessages = $e->getMessage();
            } else {
                $messages = array_unique(explode("\n", $e->getMessage()));
                $allMessages = '';
                foreach ($messages as $message) {
                    $this->_getSession()->addError($message);
                    $allMessages .= $message . "\n";
                }
            }

            $url = $this->_getSession()->getRedirectUrl(true);
            if (!$url) {
                $url = Mage::helper('checkout/cart')->getCartUrl();
            }

            $this->_sendJson(array(
                'redirectUrl' => $url,
                'message' => __($allMessages)
            ));
        }
        catch (Exception $e) {
            $message = 'Can not add item to shopping cart' . $e->getMessage();
            $this->_getSession()->addException($e, __($message));
            
            $this->_sendJson(array(
                'redirectUrl' => $this->_getRefererUrl(),
                'message' => __($message)
            ));
        }
    }

    /**
     * Update shoping cart data action
     */
    public function updatePostAction()
    {
		
        $isAjaxProRequest = $this->getRequest()->getParam('ajaxpro', false);
        if ((!$isAjaxProRequest && !$this->getRequest()->isXmlHttpRequest()) ||
			!$this->getRequest()->isXmlHttpRequest() ||
			!Mage::getStoreConfig('ajaxcart/general/enabled')) {
			
            return  parent::updatePostAction();
        }

        try {
            
            $this->_updateLayout($this->getRequest()->getParam('handles'));
            
            $cartData = $this->getRequest()->getParam('cart');
            if (is_array($cartData)) {
                $cart = $this->_getCart();
                $cart->updateItems($cartData)
                    ->save();
            }
            if (0 === $cart->getQuote()->getItemsCount()) {
                return;
            }
            $this->_getSession()->setCartWasUpdated(true);


            if ($this->_getSession()->getQuote()->getHasError()) {
                $this->_getSession()->getQuote()->setMessages(array());
                $this->_getSession()->getQuote()->setHasError(false);
                return; //reload shopping cart page
            }
            $this->_getSession()->getQuote()->setMessages(array());
            return $this->_sendJson($this->_generateResponse(__('Update successful'), 'update'));
        }
        catch (Exception $e) {
            $message = $e->getMessage();
        }
        $this->_sendJson(array(
            //'redirectUrl' => $this->_getRefererUrl(),
            'message' => __($message)
        ));
    }
    /**
     * Delete shoping cart item action
     */
	 
    public function deleteAction()
    {
        $isAjaxProRequest = $this->getRequest()->getParam('ajaxpro', false);
        if ((!$isAjaxProRequest && !$this->getRequest()->isXmlHttpRequest()) ||
			!$this->getRequest()->isXmlHttpRequest() ||
			!Mage::getStoreConfig('ajaxcart/general/enabled')) {
			
            return parent::deleteAction();
        }
        
        $id = (int) $this->getRequest()->getParam('id');
        if ($id) {
            try {
                $cart = $this->_getCart();
                $cart->removeItem($id)->save();
            } catch (Exception $e) {
                //$this->_getSession()->addError(__('Cannot remove item'));
                $this->_sendJson(array(
                    'redirectUrl' => Mage::getUrl('*/*'),
                    'message' => __('Cannot remove item')
                ));
            }
			return $this->_sendJson($this->_generateResponse(__('Delete successful'), 'update'));
        }
        $this->_sendJson(array(
            'redirectUrl' => Mage::getUrl('*/*'),
            'message' => __('set id')
        ));
    }

	protected $_maxItemCount = 4;
	protected $_crosssell;
    /**
     * Get crosssell items
     *
     * @return array
     */
   
	 public function getItems()
    {
	
		$this->_crosssell = new Mage_Checkout_Block_Cart_Crosssell();
		
       // $items = $this->_crosssell->getItems();
        $items = $this->_crosssell->getData('items');
        if (is_null($items)) {
            $items = array();
            if ($ninProductIds = $this->_getCartProductIds()) {
				
                if ($lastAdded = (int) $this->_getLastAddedProductId()) {
                    $collection = $this->_getCollection()
                        ->addProductFilter($lastAdded);
                    if (!empty($ninProductIds)) {
                        $collection->addExcludeProductFilter($ninProductIds);
                    }
                    $collection->setPositionOrder()->load();

                    foreach ($collection as $item) {
                        $ninProductIds[] = $item->getId();
                        $items[] = $item;
                    }
                }
				
                if (count($items)<$this->_maxItemCount) {
                    $collection = $this->_getCollection()
                        ->addProductFilter($this->_getCartProductIds())
                        ->addExcludeProductFilter($ninProductIds)
                        ->setPageSize($this->_maxItemCount-count($items))
                        ->setGroupBy()
                        ->setPositionOrder()
                        ->load();
                    foreach ($collection as $item) {
                        $items[] = $item;
                    }
                }
				
            }
			
           // $this->_crosssell->setData('items', $items);
        }
		
		$arrItems = array();
		$Product = Mage::getModel('catalog/product');
		if($items){
			foreach($items as $item){
				$Product->load($item->getId());
				$arrTmp['name'] 	= $Product->getName();
				$arrTmp['urlImg'] 	= $Product->getImageUrl();
				$arrTmp['url'] 		= Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK) . $Product->getUrlPath();
				$arrTmp['price'] 	= '$' . sprintf("%10.2f", $Product->getPrice());
				$arrItems[] = $arrTmp;
			}
		}
        return $arrItems;
    }

    /**
     * Count items
     *
     * @return int
     */
    public function getItemCount()
    {
		//echo count($this->getItems());
        return count($this->getItems());
    }

    /**
     * Get ids of products that are in cart
     *
     * @return array
     */
    protected function _getCartProductIds()
    {
       // $ids = $this->getData('_cart_product_ids');
        if (is_null($ids)) {
            $ids = array();
            foreach ($this->getQuote()->getAllItems() as $item) {
                if ($product = $item->getProduct()) {
                    $ids[] = $product->getId();
                }
            }
            //$this->setData('_cart_product_ids', $ids);
        }
		
        return $ids;
    }

    /**
     * Get last product ID that was added to cart and remove this information from session
     *
     * @return int
     */
    protected function _getLastAddedProductId()
    {
        return Mage::getSingleton('checkout/session')->getLastAddedProductId(true);
    }

    /**
     * Get quote instance
     *
     * @return Mage_Sales_Model_Quote
     */
    public function getQuote()
    {
        return Mage::getSingleton('checkout/session')->getQuote();
    }

    /**
     * Get crosssell products collection
     *
     * @return Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Link_Product_Collection
     */
    protected function _getCollection()
    {
        $collection = Mage::getModel('catalog/product_link')->useCrossSellLinks()
            ->getProductCollection()
            ->setStoreId(Mage::app()->getStore()->getId())
            ->addStoreFilter()
            ->setPageSize($this->_maxItemCount);
		
        //$this->_addProductAttributesAndPrices($collection);

       // Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($collection);
        //Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
       // Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);

        return $collection;
    }
    
}